

/*
 * @(#)MaintUserImportDataAction.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.user.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jxl.Sheet;
import jxl.Workbook;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.dcivision.dms.core.RootOperationManager;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.ErrorConstant;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.SystemFunctionConstant;
import com.dcivision.framework.SystemParameterConstant;
import com.dcivision.framework.SystemParameterFactory;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.Utility;
import com.dcivision.framework.web.AbstractActionForm;
import com.dcivision.framework.web.AbstractMaintAction;
import com.dcivision.staff.bean.StaffRecord;
import com.dcivision.staff.dao.StaffRecordDAObject;
import com.dcivision.user.bean.MtmUserRecordUserGroup;
import com.dcivision.user.bean.MtmUserRecordUserRole;
import com.dcivision.user.bean.UserGroup;
import com.dcivision.user.bean.UserRecord;
import com.dcivision.user.bean.UserRole;
import com.dcivision.user.dao.MtmUserRecordUserGroupDAObject;
import com.dcivision.user.dao.MtmUserRecordUserRoleDAObject;
import com.dcivision.user.dao.UserGroupDAObject;
import com.dcivision.user.dao.UserRecordDAObject;
import com.dcivision.user.dao.UserRoleDAObject;

/**
  MaintUserImportDataAction.java

  This class is for maint import data.

    @author          Susan liu
    @company         DCIVision Limited
    @creation date   20/07/2004
    @version         $Revision: 1.32.2.3 $
*/

public class MaintUserImportDataAction extends AbstractMaintAction {

  public static final String REVISION = "$Revision: 1.32.2.3 $";

  public MaintUserImportDataAction() {
    super();
  }

  /**
   * getMajorDAOClassName
   *
   * @return  The class name of the major DAObject will be used in this action.
   */
  public String getMajorDAOClassName() {
    return("com.dcivision.user.dao.UserRecordDAObject");
  }

  /**
   * getFunctionCode
   *
   * @return  The corresponding system function code of action.
   */
  public String getFunctionCode() {
    return(SystemFunctionConstant.SETUP_IMPORT_DATA);
  }

  public final static String MESSAGE_DATA_IMPORT = "user.message.data.import";
  
  public final static String MESSAGE_DATA_INSERTCOUNT = "user.message.data.insertcount";
  
  public final static String MESSAGE_DATA_UPDATECOUNT = "user.message.data.updatecount";
  
  public final static String MESSAGE_DATA_FAILCOUNT = "user.message.data.failcount";

  public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ServletException {
  AbstractActionForm maintForm = (AbstractActionForm)form;
   //  MaintUserRecordForm userRecordForm = (MaintUserRecordForm)form;
    request.setAttribute(GlobalConstant.FUNCTION_CODE_KEY,SystemFunctionConstant.SETUP_IMPORT_DATA);
    String opMode = (maintForm!=null) ? maintForm.getOpMode() : request.getParameter("opMode");    //maintForm.getOpMode();
    String navMode = (maintForm!=null) ? maintForm.getNavMode() : request.getParameter("navMode"); //maintForm.getNavMode();

     if ("I".equals((navMode))) {
       //  if (maintForm.getID()!=null) {
          try{
            createRecord(maintForm,"xls",request);
          } catch (ApplicationException appEx){
            super.handleApplicationException(request,appEx);
        //  }
         }
     }

    return mapping.findForward("I");
      //return super.execute(mapping, form, request, response);
  }

  /**
   * createRecord
   *
   * create a new user record according to the information in the staffrecordform
   *
   * @param obj
   * @param uploadType
   * @param request
   * @throws ApplicationException
   */
  public void createRecord(AbstractActionForm obj,String uploadType, HttpServletRequest request)
     throws ApplicationException {
    try {
      FileOutputStream fos = null;
      MaintUserImportDataForm maintform = (MaintUserImportDataForm) obj;
      String path = SystemParameterFactory.getSystemParameter(SystemParameterConstant.FORM_ATTACHMENT_PHYSICAL_PATH);

      /*
       * Update Code Start
       * Author			Jim.Zhou
       * Date			2006/04/19
       * Bug			#5147
       */
      if (maintform.getUploadFile()==null){
    	 log.info("NullPointerException : maintform.uploadFile is null.");
         throw new ApplicationException("user.error.errorfile");
      }
      /*
       * Update Code End
       */
       File file = new File(path + File.separator + maintform.getUploadFile().getFileName());
       if (!file.getParentFile().exists()) {
         file.getParentFile().mkdirs();
       }
      if (maintform.getUploadFile()!= null) {
        if ((maintform.getUploadFile().getFileName().indexOf(".") > 1)&&(maintform.getUploadFile().getFileName().substring(maintform.getUploadFile().getFileName().indexOf("."), maintform.getUploadFile().getFileName().length()).equals(".xls"))) {
          fos = new FileOutputStream(path + File.separator + maintform.getUploadFile().getFileName());
        } else {
          fos = null;
        }
      } else {
        throw new ApplicationException(ErrorConstant.USER_IMPORT_DATA_FAIL);
      }
      InputStream inputStream = null;
      try {
         if (fos != null) {
            inputStream = maintform.getUploadFile().getInputStream();
            int bufferSize = 8192;
            byte[] buffer = new byte[bufferSize];
            int length = -1;
            while ( (length = inputStream.read(buffer, 0, bufferSize)) != -1) {
              fos.write(buffer, 0, length);
          }
          fos.flush();
        }
       if (!uploadType.equals("image")){
         if (maintform.getUploadFile().getFileName().indexOf(".")!=-1){

           if (maintform.getUploadFile().getFileName().substring(maintform.getUploadFile().getFileName().indexOf("."),maintform.getUploadFile().getFileName().length()).equals(".xls")){
            InputStream is = new FileInputStream(file);
            jxl.Workbook rwb = Workbook.getWorkbook(is);
            Sheet[] SheetArray = rwb.getSheets();
            Sheet rs = rwb.getSheet(0);
            if(rs.getRows()<=1){
              throw new ApplicationException(ErrorConstant.USER_FILE_IS_EMPTY);
            }
            analyseFileToDB(maintform, request);
           } else {
          log.info("Uploaded File Error: Invalid File Format, please upload Excel File. ");
          throw new ApplicationException("user.error.errorfile");
             }
         } else {
              throw new ApplicationException("user.error.errorfile");
           }
       }

      } catch (IOException e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.USER_IMPORT_DATA_FAIL);
        } finally {
           try {
            if (inputStream != null) {
              inputStream.close();
            }
           } catch (IOException ioe) {}
          try {
          if (fos != null) {
            fos.close();
          }
          } catch (IOException ioe) {}
        }
    } catch (ApplicationException appEx) {
      log.error(appEx, appEx);
      throw appEx;
    } catch (Exception e) {
      log.error(e, e);
      /*
       * Update Code Start
       * Author			Jim.Zhou
       * Date			2006/04/18
       * Bug			#5147
       */
      throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, e, e.toString());
      /*
       * Update Code End
       */
    } finally {
    //       try { conn.close(); } catch (Exception ignore) {} finally { conn = null; }
    }
  }


  /**
   * @deprecated
   * analyseFileToDB
   *
   * analyse the file's format and update to DB
   *
   * @param obj
   * @param uploadType
   * @param request
   * @throws ApplicationException
   * 
   */
  public void analyseFileToDB(AbstractActionForm obj, String uploadType, HttpServletRequest request) throws ApplicationException {
    try {
  
      com.dcivision.user.web.MaintUserImportDataForm maintform = (com.dcivision.user.web.MaintUserImportDataForm) obj;
      com.dcivision.user.dao.UserRecordDAObject userRecordDAObject = new com.dcivision.user.dao.UserRecordDAObject(this.getSessionContainer(request), this.getConnection(request));
      com.dcivision.staff.dao.StaffRecordDAObject staffRecordDAObject = new com.dcivision.staff.dao.StaffRecordDAObject(this.getSessionContainer(request), this.getConnection(request));

      UserGroupDAObject userGroupDAObject = new UserGroupDAObject(this.getSessionContainer(request), this.getConnection(request));
      MtmUserRecordUserGroupDAObject mtmUserRecordUserGroupDAObject = new MtmUserRecordUserGroupDAObject(this.getSessionContainer(request), this.getConnection(request));

      UserRoleDAObject userRoleDAObject = new UserRoleDAObject(this.getSessionContainer(request), this.getConnection(request));
      MtmUserRecordUserRoleDAObject mtmUserRecordUserRoleDAObject = new MtmUserRecordUserRoleDAObject(this.getSessionContainer(request), this.getConnection(request));
      
      com.dcivision.dms.core.RootOperationManager rootOpMgr = new com.dcivision.dms.core.RootOperationManager(this.getSessionContainer(request), this.getConnection(request));
      
      String path = SystemParameterFactory.getSystemParameter(SystemParameterConstant.FORM_ATTACHMENT_PHYSICAL_PATH);
      if (maintform.getUploadFile() != null) {

        File file = new File(path + File.separator + maintform.getUploadFile().getFileName());
        InputStream is = new FileInputStream(file);
        jxl.Workbook rwb = Workbook.getWorkbook(is);
        Sheet[] SheetArray = rwb.getSheets();

//        try {
//          this.validatorXSL(rwb);
//        } catch (ApplicationException ex) {
//          throw new ApplicationException("errors.dms.file_error");
//        }
        this.validatorXSL(rwb);

        int insertCounter = 0;
        int updateCounter = 0;

        for (int ii = 0; ii < SheetArray.length; ii++) {

          Sheet rs = rwb.getSheet(0);
          for (int j = 1; j < rs.getRows(); j++) {
            String loginName = rs.getCell(0, j).getContents();
            String lastName  = rs.getCell(1, j).getContents();
            String firstName = rs.getCell(2, j).getContents();
            String email     = rs.getCell(3, j).getContents();
            String group     = rs.getCell(4, j).getContents();
            String role      = rs.getCell(5, j).getContents();
            /*
             * Update Code Start
             * Author					Jim.Zhou
             * Date						2006/06/06
             * Bug						#4015
             */
            if (Utility.isEmpty(loginName) && Utility.isEmpty(lastName) && Utility.isEmpty(firstName) && Utility.isEmpty(email) && Utility.isEmpty(group) && Utility.isEmpty(role)){
            	continue;
            }
            StaffRecord staffRecord = createStaffRecord(staffRecordDAObject, null);
            UserRecord userRecord = (UserRecord)userRecordDAObject.getByLogin(loginName);
            if (userRecord!=null) {
              userRecord = updateUserRecord(userRecordDAObject, staffRecord, userRecord, null);
              
              updateCounter++;
            }else {
              userRecord = createUserRecord(userRecordDAObject, rootOpMgr, null, staffRecord);              
              
              insertCounter++;
            }
            /*lee.lv mask by bug 4311*/
            /*
            UserRecord userRecord = (UserRecord)userRecordDAObject.getByLogin(loginName);
            StaffRecord staffRecord = null;
            if (userRecord != null) {
              try {
                staffRecord = (StaffRecord)staffRecordDAObject.getObjectByID(userRecord.getUserLinkID());
              }catch (Exception ex) {
                staffRecord = null;
              }
              if (staffRecord != null) {
                staffRecord.setStaffCode(loginName);
                staffRecord.setLastName(lastName);
                staffRecord.setFirstName(firstName);
                staffRecord.setFullName(firstName + " " + lastName);
                staffRecord.setEmail(email);
                staffRecord.setStatus("A");
                staffRecord = (StaffRecord) staffRecordDAObject.updateByFile(staffRecord);
              }else {
                staffRecord = new StaffRecord();
                staffRecord.setStaffCode(loginName);
                staffRecord.setLastName(lastName);
                staffRecord.setFirstName(firstName);
                staffRecord.setFullName(firstName + " " + lastName);
                staffRecord.setEmail(email);
                staffRecord.setStatus("A");
                staffRecord.setSalutationID(new Integer(1));
                staffRecord.setGender("M");
                staffRecord = (StaffRecord) staffRecordDAObject.insertByFile(staffRecord);
              }
              
              userRecord.setLoginName(loginName);
              userRecord.setLastName(lastName);
              userRecord.setFirstName(firstName);
              userRecord.setFullName(firstName + " " + lastName);
              userRecord.setEmail(email);
              userRecord.setUserLinkID(staffRecord.getID());
              userRecord.setStatus("A");
              userRecord = (UserRecord) userRecordDAObject.updateByFile(userRecord);
              
              updateCounter++;
            } else {
              staffRecord = new StaffRecord();
              staffRecord.setStaffCode(loginName);
              staffRecord.setLastName(lastName);
              staffRecord.setFirstName(firstName);
              staffRecord.setFullName(firstName + " " + lastName);
              staffRecord.setEmail(email);
              staffRecord.setStatus("A");
              staffRecord.setSalutationID(new Integer(1));
              staffRecord.setGender("M");
              staffRecord = (StaffRecord) staffRecordDAObject.insertByFile(staffRecord);
              
              userRecord = new UserRecord();              
              userRecord.setLoginName(loginName);
              userRecord.setLastName(lastName);
              userRecord.setFirstName(firstName);
              userRecord.setFullName(firstName + " " + lastName);
              userRecord.setEmail(email);
              userRecord.setFailedAttempt(new Integer("0"));
              userRecord.setMaxAttempt(null);
              userRecord.setPwdExpiryDay(null);
              userRecord.setUserLinkID(staffRecord.getID());
              userRecord.setUserType("S");
              userRecord.setStatus("A");
              userRecord.setLoginPwd("password");
              userRecord.setModifyLoginPwd((SystemParameterFactory.getSystemParameterBoolean(SystemParameterConstant.SYSTEM_MODIFY_PASSWROD)? "Y" : "N"));
              userRecord = (UserRecord) userRecordDAObject.insertByFile(userRecord);
              
              // Create personal folder.              
              rootOpMgr.createDefaultPersonalRootPointForUser(userRecord.getID());              
              
              insertCounter++;
            }
            */
                        
            String[] splitAryGroup = TextUtility.splitString(TextUtility.noNull(group).trim(), ",");
            if (!Utility.isEmpty(splitAryGroup)) {
              for (int i = 0; i < splitAryGroup.length; i++) {
                UserGroup userGroup = null;
                if (!Utility.isEmpty(userGroupDAObject.getObjectByGroupName(splitAryGroup[i]))) {
                  userGroup = (UserGroup) userGroupDAObject.getObjectByGroupName(splitAryGroup[i]);
                } else {
                  userGroup = new UserGroup();
                  userGroup.setOwnerUserRecordID(this.getSessionContainer(request).getUserRecordID());
                  userGroup.setGroupType(UserGroup.GROUP_TYPE_PUBLIC);
                  userGroup.setGroupName(splitAryGroup[i]);
                  userGroup = (UserGroup) userGroupDAObject.insertObject(userGroup);
                  //this.commit(request);
                }
                if (Utility.isEmpty(mtmUserRecordUserGroupDAObject.getListByUserRecordID(userRecord.getID(), userGroup.getID()))) {
                  MtmUserRecordUserGroup mtmUserRecordUserGroup = new MtmUserRecordUserGroup();
                  mtmUserRecordUserGroup.setUserGroupID(userGroup.getID());
                  mtmUserRecordUserGroup.setUserRecordID(userRecord.getID());
                  mtmUserRecordUserGroup = (MtmUserRecordUserGroup) mtmUserRecordUserGroupDAObject.insertObject(mtmUserRecordUserGroup);
                  //this.commit(request);
                }
              }
            }
                        
            String[] splitAryRole = TextUtility.splitString(TextUtility.noNull(role).trim(), ",");
            if (!Utility.isEmpty(splitAryRole)) {
              for (int i = 0; i < splitAryRole.length; i++) {
                UserRole userRole = null;
                if (!Utility.isEmpty(userRoleDAObject.getObjectByRoleName(splitAryRole[i]))) {
                  userRole = (UserRole) userRoleDAObject.getObjectByRoleName(splitAryRole[i]);
                } else {
                  userRole = new UserRole();
                  userRole.setRoleName(splitAryRole[i]);
                  userRole.setRoleType(UserRole.ROLE_TYPE_USER_DEFINED);
                  userRole = (UserRole) userRoleDAObject.insertObject(userRole);
                  //this.commit(request);
                }
                if (Utility.isEmpty(mtmUserRecordUserRoleDAObject.getListByUserRecordID(userRecord.getID(), userRole.getID()))) {
                  MtmUserRecordUserRole mtmUserRecordUserRole = new MtmUserRecordUserRole();
                  mtmUserRecordUserRole.setUserRoleID(userRole.getID());
                  mtmUserRecordUserRole.setUserRecordID(userRecord.getID());
                  mtmUserRecordUserRole = (MtmUserRecordUserRole) mtmUserRecordUserRoleDAObject.insertObject(mtmUserRecordUserRole);
                  //this.commit(request);
                }
              }
            }

          }
        }
       
        addMessage(request, MESSAGE_DATA_IMPORT);
        addMessage(request, MESSAGE_DATA_INSERTCOUNT, new Integer(insertCounter));
        addMessage(request, MESSAGE_DATA_UPDATECOUNT, new Integer(updateCounter));
        
        this.commit(request);
      }
    } catch (ApplicationException ex) {
      this.rollback(request);
      throw ex;
    } catch (Exception e) {
      this.rollback(request);
      log.error(e);
      throw new ApplicationException(ErrorConstant.DB_RECORD_NOT_FOUND_ERROR);
    } finally {
      //      try { conn.close(); } catch (Exception ignore) {} finally { conn = null; }
    }
  }
  
  /*
  public void  analyseFileToDB(AbstractActionForm obj,String uploadType, HttpServletRequest request)
      throws ApplicationException {
    try {
      Cell cell = null;
      String cellString = null;
      boolean elementTag = false;
      com.dcivision.staff.bean.StaffRecord staffRecord = new com.dcivision.staff.bean.StaffRecord();
      com.dcivision.user.bean.UserRecord  userRecord = new com.dcivision.user.bean.UserRecord();
      com.dcivision.user.web.MaintUserImportDataForm maintform = (com.dcivision.user.web.MaintUserImportDataForm) obj;
      com.dcivision.user.dao.UserRecordDAObject userRecordDAObject = new  com.dcivision.user.dao.UserRecordDAObject(this.getSessionContainer(request), this.getConnection(request));
      com.dcivision.staff.dao.StaffRecordDAObject staffRecordDAObject = new  com.dcivision.staff.dao.StaffRecordDAObject(this.getSessionContainer(request), this.getConnection(request));
      
      UserGroup userGroup = new UserGroup();
      MtmUserRecordUserGroup mtmUserRecordUserGroup = new MtmUserRecordUserGroup();
      UserGroupDAObject userGroupDAObject = new UserGroupDAObject(this.getSessionContainer(request), this.getConnection(request));
      MtmUserRecordUserGroupDAObject mtmUserRecordUserGroupDAObject = new MtmUserRecordUserGroupDAObject(this.getSessionContainer(request), this.getConnection(request));
      
      UserRole userRole = new UserRole();
      MtmUserRecordUserRole mtmUserRecordUserRole = new MtmUserRecordUserRole();
      UserRoleDAObject userRoleDAObject = new UserRoleDAObject(this.getSessionContainer(request), this.getConnection(request));
      MtmUserRecordUserRoleDAObject mtmUserRecordUserRoleDAObject = new MtmUserRecordUserRoleDAObject(this.getSessionContainer(request), this.getConnection(request));

      String path = SystemParameterFactory.getSystemParameter(SystemParameterConstant.FORM_ATTACHMENT_PHYSICAL_PATH);
      if (maintform.getUploadFile()!= null) {

       File file = new File(path + File.separator + maintform.getUploadFile().getFileName());
       InputStream is = new FileInputStream(file);
       jxl.Workbook rwb = Workbook.getWorkbook(is);
       Sheet[] SheetArray = rwb.getSheets();
       
       try{
      	 this.validatorXSL(rwb);
       } catch(ApplicationException ex){
      	 throw new ApplicationException("errors.dms.file_error");
       }
       
       int insertCounter = 0;
       int updateCounter = 0;

       for (int ii=0;ii<SheetArray.length;ii++){

        Sheet rs = rwb.getSheet(0);
        for (int j=1;j<rs.getRows();j++){
          cell = rs.getCell(0, j);
          cellString = cell.getContents();
          userRecord.setLoginName(cellString);
          staffRecord.setStaffCode(cellString);

          cell = rs.getCell(1, j);
          cellString = cell.getContents();
          staffRecord.setLastName(cellString);
          userRecord.setLastName(cellString);

          cell = rs.getCell(2, j);
          cellString = cell.getContents();
          staffRecord.setFirstName(cellString);
          userRecord.setFirstName(cellString);

          userRecord.setFullName(userRecord.getFirstName() + " " +
                                 userRecord.getLastName());
          staffRecord.setFullName(userRecord.getFirstName() + " " +
                                  userRecord.getLastName());

          cell = rs.getCell(3, j);
          cellString = cell.getContents();
          userRecord.setEmail(cellString);
          staffRecord.setEmail(cellString);

          userRecord.setFailedAttempt(new Integer("0"));

          userRecord.setMaxAttempt(null);

          userRecord.setPwdExpiryDay(null);

          userRecord.setStatus("A");
          staffRecord.setStatus("A");
          staffRecord.setSalutationID(new Integer(1));
          staffRecord.setGender("M");
          userRecord.setUserType("S");
          
          if (SystemParameterFactory.getSystemParameterBoolean(SystemParameterConstant.SYSTEM_MODIFY_PASSWROD)){
        		userRecord.setModifyLoginPwd("Y");
        	} else {
        		userRecord.setModifyLoginPwd("N");
        	}

          if (userRecordDAObject.getByLogin(userRecord.getLoginName()) != null) {
            userRecordDAObject.updateByFile(userRecord);
            userRecord = (UserRecord) userRecordDAObject.getByLogin(userRecord.getLoginName());
            staffRecord.setID(userRecord.getUserLinkID());
            staffRecordDAObject.updateByFile(staffRecord);
            updateCounter++;
          }  else {
            staffRecord = (StaffRecord) staffRecordDAObject.insertByFile(staffRecord);
            userRecord.setUserLinkID(staffRecord.getID());
            userRecord.setLoginPwd("password");
            userRecord = (UserRecord)userRecordDAObject.insertByFile(userRecord);
            insertCounter++;
          }
          
          cell = rs.getCell(4, j);
          cellString = cell.getContents();
          String[] splitAryGroup = TextUtility.splitString(TextUtility.noNull(cellString).trim(), ",");
          if(!Utility.isEmpty(splitAryGroup)){
            for (int i=0 ; i<splitAryGroup.length ; i++){
          	  if(!Utility.isEmpty(userGroupDAObject.getObjectByGroupName((String)splitAryGroup[i]))){
          	    userGroup = (UserGroup)userGroupDAObject.getObjectByGroupName((String)splitAryGroup[i]);        	  
          	  }else{
          	    userGroup.setOwnerUserRecordID(this.getSessionContainer(request).getUserRecordID());
          	    userGroup.setGroupType(UserGroup.GROUP_TYPE_PUBLIC);
          	    userGroup.setGroupName((String)splitAryGroup[i]);
          	    userGroup = (UserGroup)userGroupDAObject.insertObject(userGroup);
          	    this.commit(request);
          	  }
          	  if(Utility.isEmpty(mtmUserRecordUserGroupDAObject.getListByUserRecordID(userRecord.getID(),userGroup.getID()))){
          	    mtmUserRecordUserGroup.setUserGroupID(userGroup.getID());
          	    mtmUserRecordUserGroup.setUserRecordID(userRecord.getID());
          	    mtmUserRecordUserGroup = (MtmUserRecordUserGroup)mtmUserRecordUserGroupDAObject.insertObject(mtmUserRecordUserGroup);
          	    this.commit(request);
          	  }
            }
          }
          
          cell = rs.getCell(5, j);
          cellString = cell.getContents();
          String[] splitAryRole = TextUtility.splitString(TextUtility.noNull(cellString).trim(), ",");
          if(!Utility.isEmpty(splitAryRole)){
            for (int i=0 ; i<splitAryRole.length ; i++){
          	  if(!Utility.isEmpty(userRoleDAObject.getObjectByRoleName((String)splitAryRole[i]))){
          	    userRole = (UserRole)userRoleDAObject.getObjectByRoleName((String)splitAryRole[i]);        	  
          	  }else{
          	    userRole.setRoleName((String)splitAryRole[i]);
          	    userRole.setRoleType(UserRole.ROLE_TYPE_USER_DEFINED);
          	    userRole = (UserRole)userRoleDAObject.insertObject(userRole);
          	    this.commit(request);
          	  }
          	  if(Utility.isEmpty(mtmUserRecordUserRoleDAObject.getListByUserRecordID(userRecord.getID(),userRole.getID()))){
          	    mtmUserRecordUserRole.setUserRoleID(userRole.getID());
          	    mtmUserRecordUserRole.setUserRecordID(userRecord.getID());
          	    mtmUserRecordUserRole = (MtmUserRecordUserRole)mtmUserRecordUserRoleDAObject.insertObject(mtmUserRecordUserRole);
          	    this.commit(request);
          	  }
          	}
          }
          
        }
       }

       //Create personal folder.
       com.dcivision.dms.core.RootOperationManager rootOpMgr = new com.dcivision.dms.core.RootOperationManager(this.getSessionContainer(request), this.getConnection(request));
       rootOpMgr.createDefaultPersonalRootPointForUser(this.getSessionContainer(request).getUserRecordID());

       addMessage(request, MESSAGE_DATA_IMPORT);
       addMessage(request, MESSAGE_DATA_INSERTCOUNT, new Integer(insertCounter));
       addMessage(request, MESSAGE_DATA_UPDATECOUNT, new Integer(updateCounter));
    }
   } catch(ApplicationException ex){
  	 if ("errors.dms.file_error".equals(ex.getMsgCode())) throw new ApplicationException("errors.dms.file_error");
   } catch (Exception e) {
       log.error(e);
       throw new ApplicationException(ErrorConstant.DB_RECORD_NOT_FOUND_ERROR);
    } finally {
     //      try { conn.close(); } catch (Exception ignore) {} finally { conn = null; }
      }
 }

  */
  /**
   * analyseFileToDB
   *
   * analyse the file's format and update to DB
   *
   * @param obj
   * @param request
   * @throws ApplicationException
   * 
   */
  public void analyseFileToDB(AbstractActionForm obj, HttpServletRequest request)
      throws ApplicationException {
    try {

      MaintUserImportDataForm maintform = (MaintUserImportDataForm) obj;
      UserRecordDAObject userRecordDAObject = new UserRecordDAObject(this
          .getSessionContainer(request), this.getConnection(request));
      StaffRecordDAObject staffRecordDAObject = new StaffRecordDAObject(this
          .getSessionContainer(request), this.getConnection(request));

      UserGroupDAObject userGroupDAObject = new UserGroupDAObject(
          this.getSessionContainer(request), this.getConnection(request));
      MtmUserRecordUserGroupDAObject mtmUserRecordUserGroupDAObject = new MtmUserRecordUserGroupDAObject(
          this.getSessionContainer(request), this.getConnection(request));

      UserRoleDAObject userRoleDAObject = new UserRoleDAObject(this.getSessionContainer(request),
          this.getConnection(request));
      MtmUserRecordUserRoleDAObject mtmUserRecordUserRoleDAObject = new MtmUserRecordUserRoleDAObject(
          this.getSessionContainer(request), this.getConnection(request));

      com.dcivision.dms.core.RootOperationManager rootOpMgr = new com.dcivision.dms.core.RootOperationManager(
          this.getSessionContainer(request), this.getConnection(request));

      String path = SystemParameterFactory
          .getSystemParameter(SystemParameterConstant.FORM_ATTACHMENT_PHYSICAL_PATH);
      if (maintform.getUploadFile() != null) {

        File file = new File(path + File.separator + maintform.getUploadFile().getFileName());
        InputStream is = new FileInputStream(file);
        jxl.Workbook rwb = Workbook.getWorkbook(is);
        Sheet[] SheetArray = rwb.getSheets();

        int insertCounter = 0;
        
        int updateCounter = 0;

        int failCounter = 0;

        List failRecordList = new ArrayList();

        for (int ii = 0; ii < SheetArray.length; ii++) {

          Sheet rs = rwb.getSheet(0);
          for (int j = 1; j < rs.getRows(); j++) {
            String loginName = rs.getCell(0, j).getContents();
            String lastName = rs.getCell(1, j).getContents();
            String firstName = rs.getCell(2, j).getContents();
            String email = rs.getCell(3, j).getContents();
            String group = rs.getCell(4, j).getContents();
            String role = rs.getCell(5, j).getContents();

            boolean isInsert = false;
            boolean isUpdate = false;
            if (Utility.isEmpty(loginName) && Utility.isEmpty(lastName)
                && Utility.isEmpty(firstName) && Utility.isEmpty(email) && Utility.isEmpty(group)
                && Utility.isEmpty(role)) {
              continue;
            }
            ImportData data = new ImportData(loginName, lastName, firstName, email, group, role);
            try {

              // validate import data
              this.validateData(data);

              // perform staffRecord
              StaffRecord staffRecord = createStaffRecord(staffRecordDAObject, data);

              // perform userRecord
              UserRecord userRecord = (UserRecord) userRecordDAObject.getByLogin(loginName);
              if (userRecord != null) {
                userRecord = updateUserRecord(userRecordDAObject, staffRecord, userRecord, data);

                isUpdate = true;
              }
              else {
                userRecord = createUserRecord(userRecordDAObject, rootOpMgr, data, staffRecord);

                isInsert = true;
              }
              // group
              performUserGroup(request, userGroupDAObject, mtmUserRecordUserGroupDAObject, group,
                  userRecord);
              // role
              performUserRole(userRoleDAObject, mtmUserRecordUserRoleDAObject, role, userRecord);

              this.commit(request);

              if (isInsert) {
                insertCounter++;
              }
              if (isUpdate) {
                updateCounter++;
              }

            }
            catch (Exception e) {
              log.error(e.toString(), e);
              this.rollback(request);
              failCounter++;

              failRecordList.add(data);
              continue;
            }
          }
        }
        
       
        if (insertCounter > 0) {
          addMessage(request, MESSAGE_DATA_INSERTCOUNT, new Integer(insertCounter));
        }
        if (updateCounter > 0) {
          addMessage(request, MESSAGE_DATA_UPDATECOUNT, new Integer(updateCounter));
        }
        if(failCounter>0){
          request.setAttribute("havafailRecord", "true");
          exportFailRecord2request(failRecordList, request);
          addMessage(request, MESSAGE_DATA_FAILCOUNT, new Integer(failCounter));          
        }

      }
    }
    catch (Exception e) {
      log.error(e.toString(), e);
      throw new ApplicationException("user.error.errorfile");
    }
  }
  
/**
 * 
 * @param failRecordList
 * @param request
 */
  private void exportFailRecord2request(List failRecordList, HttpServletRequest request) {
    StringBuffer sb = new StringBuffer();
    for(int i=0;i<failRecordList.size();i++){
      ImportData data =(ImportData)failRecordList.get(i);
      sb.append("<tr align=\"center\" >");
      sb.append("<td width=\"10%\" style=\"width:100;word-wrap:break-word;table-layout:fixed;\">"+data.getLoginName()+"</td>");
      sb.append("<td width=\"10%\" style=\"width:100;word-wrap:break-word;table-layout:fixed;\">"+data.getLastName()+"</td>");
      sb.append("<td width=\"10%\" style=\"width:100;word-wrap:break-word;table-layout:fixed;\">"+data.getFirstName()+"</td>");
      sb.append("<td width=\"10%\" style=\"width:100;word-wrap:break-word;table-layout:fixed;\">"+data.getEMail()+"</td>");
      sb.append("<td width=\"10%\" style=\"width:100;word-wrap:break-word;table-layout:fixed;\">"+data.getGroups()+"</td>");
      sb.append("<td width=\"10%\" style=\"width:100;word-wrap:break-word;table-layout:fixed;\">"+data.getRoles()+"</td>");
      sb.append("<td  width=\"40%\" style=\"color: red;\" style=\"width:150;word-wrap:break-word;table-layout:fixed;\">"+data.getExceptionInfo()+"</td>");
      sb.append("</tr>");    
    }
    request.setAttribute("failRecord", sb.toString());
    
  }

  /**
   * @param userRecordDAObject
   * @param staffRecord
   * @param userRecord
   * @param data 
   * @return
   * @throws ApplicationException
   */
  private UserRecord updateUserRecord(UserRecordDAObject userRecordDAObject, StaffRecord staffRecord, UserRecord userRecord, ImportData data) throws ApplicationException {
    userRecord.setLoginName(data.getLoginName());
    userRecord.setLastName(data.getLastName());
    userRecord.setFirstName(data.getFirstName());
    userRecord.setFullName(data.getFirstName() + " " + data.getLastName());
    userRecord.setEmail(data.getEMail());
    userRecord.setUserLinkID(staffRecord.getID());
    userRecord.setStatus("A");
    userRecord = (UserRecord) userRecordDAObject.updateByFile(userRecord);
    return userRecord;
  }

  /**
   * @param userRecordDAObject
   * @param rootOpMgr
   * @param data 
   * @param staffRecord
   * @return
   * @throws NumberFormatException
   * @throws ApplicationException
   */
  private UserRecord createUserRecord(UserRecordDAObject userRecordDAObject, RootOperationManager rootOpMgr, ImportData data, StaffRecord staffRecord) throws NumberFormatException, ApplicationException {
    UserRecord userRecord;
    userRecord = new UserRecord();              
    userRecord.setLoginName(data.getLoginName());
    userRecord.setLastName(data.getLastName());
    userRecord.setFirstName(data.getFirstName());
    userRecord.setFullName(data.getFirstName() + " " + data.getLastName());
    userRecord.setEmail(data.getEMail());
    userRecord.setFailedAttempt(new Integer("0"));
    userRecord.setMaxAttempt(null);
    userRecord.setPwdExpiryDay(null);
    userRecord.setUserLinkID(staffRecord.getID());
    userRecord.setUserType("S");
    userRecord.setStatus("A");
    userRecord.setLoginPwd("password");
    userRecord.setModifyLoginPwd((SystemParameterFactory.getSystemParameterBoolean(SystemParameterConstant.SYSTEM_MODIFY_PASSWROD)? "Y" : "N"));
    userRecord = (UserRecord) userRecordDAObject.insertByFile(userRecord);
    
    // Create personal folder.              
    rootOpMgr.createDefaultPersonalRootPointForUser(userRecord.getID());
    return userRecord;
  }

  /**
   * @param userRoleDAObject
   * @param mtmUserRecordUserRoleDAObject
   * @param role
   * @param userRecord
   * @return
   * @throws ApplicationException
   */
  private void performUserRole(UserRoleDAObject userRoleDAObject, MtmUserRecordUserRoleDAObject mtmUserRecordUserRoleDAObject, String role, UserRecord userRecord) throws ApplicationException {
    String[] splitAryRole = TextUtility.splitString(TextUtility.noNull(role).trim(), ",");
    if (!Utility.isEmpty(splitAryRole)) {
      for (int i = 0; i < splitAryRole.length; i++) {
        if (Utility.isEmpty(splitAryRole[i])) {
          continue;
        }
        UserRole userRole = null;
        if (!Utility.isEmpty(userRoleDAObject.getObjectByRoleName(splitAryRole[i]))) {
          userRole = (UserRole) userRoleDAObject.getObjectByRoleName(splitAryRole[i]);
        } else {
          userRole = new UserRole();
          userRole.setRoleName(splitAryRole[i]);
          userRole.setRoleType(UserRole.ROLE_TYPE_USER_DEFINED);
          userRole = (UserRole) userRoleDAObject.insertObject(userRole);
          //this.commit(request);
        }
        if (Utility.isEmpty(mtmUserRecordUserRoleDAObject.getListByUserRecordID(userRecord.getID(), userRole.getID()))) {
          MtmUserRecordUserRole mtmUserRecordUserRole = new MtmUserRecordUserRole();
          mtmUserRecordUserRole.setUserRoleID(userRole.getID());
          mtmUserRecordUserRole.setUserRecordID(userRecord.getID());
          mtmUserRecordUserRole = (MtmUserRecordUserRole) mtmUserRecordUserRoleDAObject.insertObject(mtmUserRecordUserRole);
          //this.commit(request);
        }
      }
    }
  }

  /**
   * @param request
   * @param userGroupDAObject
   * @param mtmUserRecordUserGroupDAObject
   * @param group
   * @param userRecord
   * @return
   * @throws ApplicationException
   */
  private void performUserGroup(HttpServletRequest request, UserGroupDAObject userGroupDAObject, MtmUserRecordUserGroupDAObject mtmUserRecordUserGroupDAObject, String group, UserRecord userRecord) throws ApplicationException {
    String[] splitAryGroup = TextUtility.splitString(TextUtility.noNull(group).trim(), ",");
    if (!Utility.isEmpty(splitAryGroup)) {
      for (int i = 0; i < splitAryGroup.length; i++) {
        if (Utility.isEmpty(splitAryGroup[i])) {
          continue;
        }
        UserGroup userGroup = null;
        if (!Utility.isEmpty(userGroupDAObject.getObjectByGroupName(splitAryGroup[i]))) {
          userGroup = (UserGroup) userGroupDAObject.getObjectByGroupName(splitAryGroup[i]);
        } else {
          userGroup = new UserGroup();
          userGroup.setOwnerUserRecordID(this.getSessionContainer(request).getUserRecordID());
          userGroup.setGroupType(UserGroup.GROUP_TYPE_PUBLIC);
          userGroup.setGroupName(splitAryGroup[i]);
          userGroup = (UserGroup) userGroupDAObject.insertObject(userGroup);
          //this.commit(request);
        }
        if (Utility.isEmpty(mtmUserRecordUserGroupDAObject.getListByUserRecordID(userRecord.getID(), userGroup.getID()))) {
          MtmUserRecordUserGroup mtmUserRecordUserGroup = new MtmUserRecordUserGroup();
          mtmUserRecordUserGroup.setUserGroupID(userGroup.getID());
          mtmUserRecordUserGroup.setUserRecordID(userRecord.getID());
          mtmUserRecordUserGroup = (MtmUserRecordUserGroup) mtmUserRecordUserGroupDAObject.insertObject(mtmUserRecordUserGroup);
          //this.commit(request);
        }
      }
    }
  }

  /**
   * @param staffRecordDAObject
   * @param data 
   * @return
   * @throws ApplicationException
   */
  private StaffRecord createStaffRecord(StaffRecordDAObject staffRecordDAObject, ImportData data) throws ApplicationException {
    StaffRecord staffRecord = (StaffRecord)staffRecordDAObject.getObjectByStaffName(data.getFirstName(), data.getLastName());
    if (staffRecord==null) {
      staffRecord = new StaffRecord();
      staffRecord.setStaffCode("N/A");
      staffRecord.setLastName(data.getLastName());
      staffRecord.setFirstName(data.getFirstName());
      staffRecord.setFullName(data.getFirstName() + " " + data.getLastName());
      staffRecord.setEmail(data.getEMail());
      staffRecord.setStatus("A");
      staffRecord.setSalutationID(new Integer(1));
      staffRecord.setGender("M");
      staffRecord = (StaffRecord) staffRecordDAObject.insertByFile(staffRecord);
    }
    return staffRecord;
  }
  /**
   * createStaffRecord
   *
   * create a new staff record according to the information in the userRecordForm
   *
   * @param  userRecordForm
   * @param  request
   * @return StaffRecord
   * throws  ApplicationException
   */
  private StaffRecord createStaffRecord(MaintUserRecordForm userRecordForm, HttpServletRequest request) throws ApplicationException {
    SessionContainer sessionCon = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    StaffRecordDAObject dao = new StaffRecordDAObject(sessionCon, conn);
    StaffRecord staffRecord = new StaffRecord();


    staffRecord.setFirstName(userRecordForm.getFirstName());
    staffRecord.setLastName(userRecordForm.getLastName());
    staffRecord.setFullName(userRecordForm.getFullName());
    staffRecord.setEmail(userRecordForm.getEmail());

    staffRecord.setGender("M");
    staffRecord.setSalutationID(new Integer(1));
    staffRecord.setStaffCode("");
    staffRecord.setStatus("A");

    staffRecord = (StaffRecord)dao.insertObject(staffRecord);
    return staffRecord;
  }
  
 /**
  * @deprecated
  * @param workBook
  * @throws ApplicationException
  */
  public void validatorXSL(Workbook workBook) throws ApplicationException {
    Sheet[] sheetAry = workBook.getSheets();
    if (Utility.isEmpty(sheetAry)) {
      throw new ApplicationException();
    }
    for (int i = 0; i < sheetAry.length; i++) {
      Sheet sheet = sheetAry[i];
      int rowNo = sheet.getRows();
      for (int rn = 1; rn < rowNo; rn++) {
        /*
         * Update Code Start
         * Author			Jim.Zhou
         * Date				2006/05/08
         * Bug				#5241
         */
        // valitor Login name
        /*
         * Update Code Start
         * Author					Jim.Zhou
         * Date						2006/06/06
         * Bug						#4015
         */
        String loginName = sheet.getCell(0, rn).getContents();
        String lastName = sheet.getCell(1,rn).getContents();
        String firstName = sheet.getCell(2,rn).getContents();
        String eMail = sheet.getCell(3,rn).getContents();
        String groups = sheet.getCell(4,rn).getContents();
        String roles= sheet.getCell(5,rn).getContents();
        
        Integer loginNameLength = SystemParameterFactory.getSystemParameterInteger(SystemParameterConstant.MINIMUM_LOGIN_NAME_LENGTH);
        if (Utility.isEmpty(loginName) && Utility.isEmpty(lastName) && Utility.isEmpty(firstName) && Utility.isEmpty(eMail) && Utility.isEmpty(groups) && Utility.isEmpty(roles)){
          continue;
        }
        /*
         * Update Code End
         */
        Pattern pattern = Pattern.compile("^(([a-zA-Z0-9])+((\\.)?([a-zA-Z0-9])+)?((\\_)?([a-zA-Z0-9])+)?)$");
        Matcher matcher = pattern.matcher(loginName);
        if (!matcher.find()){
          String[] error = new String[3];
          error[0] = "" + rn;
          error[1] = "0";
          error[2] = "<br>Login name is invalid in row" + rn + " .";
          throw new ApplicationException("errors.dms.file_error",new Exception(),error);
        }
        if (Utility.isEmpty(loginName) || loginName.length() < loginNameLength.intValue() || loginName.indexOf(" ")!=-1){
          String[] error = new String[3];
          error[0] = "" + rn;
          error[1] = "0";
          error[2] = "<br>Login name must contain at least "+loginNameLength+" characters and can't contain blank character.";
          throw new ApplicationException("errors.dms.file_error",new Exception(),error);
        }
        try{
          TextUtility.stringValidation(loginName);
        } catch(ApplicationException ex){
          String[] error = new String[3];
          error[0] = "" + rn;
          error[1] = "0";
          error[2] = "<br>Login name is invaild.";
          throw new ApplicationException("errors.dms.file_error",new Exception(),error);
        }
        
        // valitor last Name
        //String lastName = sheet.getCell(1, rn).getContents();
        if (Utility.isEmpty(lastName) || Utility.isEmpty(lastName.trim())){
          String[] error = new String[3];
          error[0] = "" + rn;
          error[1] = "1";
          error[2] = "<br>Last name is required.";
          throw new ApplicationException("errors.dms.file_error",new Exception(),error);
        }
        /*     try{
         TextUtility.stringValidation(lastName);
         } catch(ApplicationException ex){
         String[] error = new String[3];
         error[0] = "" + rn;
         error[1] = "1";
         error[2] = "<br>Last name is invaild.";
         throw new ApplicationException("errors.dms.file_error",new Exception(),error);
         }
         */
        // valitor First Name
        //String firstName = sheet.getCell(2, rn).getContents();
        if (Utility.isEmpty(firstName) || Utility.isEmpty(firstName.trim())){
          String[] error = new String[3];
          error[0] = "" + rn;
          error[1] = "2";
          error[2] = "<br>First name is required.";
          throw new ApplicationException("errors.dms.file_error",new Exception(),error);
        }
        /*     try{
         TextUtility.stringValidation(firstName);
         } catch(ApplicationException ex){
         String[] error = new String[3];
         error[0] = "" + rn;
         error[1] = "2";
         error[2] = "<br>First name is invaild.";
         throw new ApplicationException("errors.dms.file_error",new Exception(),error);
         }
         */     
        
        // valitor Email name
        String email = sheet.getCell(3, rn).getContents();
        if (!Utility.isEmpty(email)) {
          if (!TextUtility.verifyEmail(email)){
            String[] error = new String[3];
            error[0] = "" + rn;
            error[1] = "3";
            error[2] = "<br>Email Address is invaild E-maiil address.";
            throw new ApplicationException("errors.dms.file_error",new Exception(),error);
          }
        }
        
        // valitor Group
        String groupCell = sheet.getCell(4, rn).getContents();
        String[] groupAry = TextUtility.splitString(TextUtility.noNull(groupCell).trim(), ",");
        if (!Utility.isEmpty(groupAry)) {
          String[] error = new String[3];
          error[0] = "" + rn;
          error[1] = "4";
          error[2] = "<br>Group  is invaild.";
          try{
            for (int groupNo = 0; groupNo < groupAry.length; groupNo++) {
              if (Utility.isEmpty(groupAry[groupNo])){
                throw new ApplicationException();
              }
              TextUtility.stringValidation(groupAry[groupNo]);
            }
          }catch(ApplicationException ex){
            throw new ApplicationException("errors.dms.file_error",new Exception(),error);
          }
        }
        
        // valitor role
        String roleCell = sheet.getCell(5, rn).getContents();
        String[] roleAry = TextUtility.splitString(TextUtility.noNull(roleCell).trim(), ",");
        if (!Utility.isEmpty(roleAry)) {
          String[] error = new String[3];
          error[0] = "" + rn;
          error[1] = "5";
          error[2] = "<br>Role  is invaild.";
          try{
            for (int roleNo = 0; roleNo < roleAry.length; roleNo++) {
              if (Utility.isEmpty(roleAry[roleNo])){
                throw new ApplicationException();
              }
              TextUtility.stringValidation(roleAry[roleNo]);
            }
          }catch(ApplicationException ex){
            throw new ApplicationException("errors.dms.file_error",new Exception(),error);
          }
        }
        /*
         * Update Code End
         */
        
      }
    }
  }
 /**
  * 
  * @param data
 * @throws ApplicationException 
  */
  private void validateData(ImportData data) throws ApplicationException {

    String loginName = data.getLoginName();
    String lastName = data.getLastName();
    String firstName = data.getFirstName();
    String eMail = data.getEMail();
    String groups = data.getGroups();
    String roles = data.getRoles();

    StringBuffer errorInfo = new StringBuffer();

    int loginNameMinLength = SystemParameterFactory.getSystemParameterInteger(
        SystemParameterConstant.MINIMUM_LOGIN_NAME_LENGTH).intValue();
    int loginNameMaxLength = 20;

    if (!loginName.matches("([a-zA-Z0-9])+((\\.)?([a-zA-Z0-9])+)?((\\_)?([a-zA-Z0-9])+)?")) {
      errorInfo.append("Login name is invalid;  ");
    }
    else if (Utility.isEmpty(loginName) || loginName.length() < loginNameMinLength
        || loginName.length() > loginNameMaxLength || loginName.indexOf(" ") != -1) {
      errorInfo.append("Login name must " + loginNameMinLength + "-" + loginNameMaxLength
          + " characters and can't contain blank character;  ");
    }
    else {
      try {
        TextUtility.stringValidation(loginName);
      }
      catch (ApplicationException ex) {
        errorInfo.append("Login name is invaild;  ");
      }
    }
    // valitor last Name
    if (Utility.isEmpty(lastName) || Utility.isEmpty(lastName.trim())) {
      errorInfo.append("Last name is required; ");
    }else if(lastName.trim().length()>99){
      errorInfo.append("Last name is too length; ");      
    }else {
      try {
        TextUtility.stringValidation(lastName);
      }
      catch (ApplicationException ex) {
        errorInfo.append("lastName is invaild;  ");
      }
    }

    // valitor First Name
    if (Utility.isEmpty(firstName) || Utility.isEmpty(firstName.trim())) {
      errorInfo.append("First name is required; ");
    }else if(firstName.trim().length()>99){
      errorInfo.append("First name is too length; ");      
    }else {
      try {
        TextUtility.stringValidation(firstName);
      }
      catch (ApplicationException ex) {
        errorInfo.append("firstName is invaild;  ");
      }
    }
    // valitor Email name
    if (!Utility.isEmpty(eMail) && !TextUtility.verifyEmail(eMail)) {
      errorInfo.append("Email Address is invaild E-maiil address; ");
    }

    // valitor Group
    String[] groupAry = TextUtility.splitString(TextUtility.noNull(groups).trim(), ",");
    if (!Utility.isEmpty(groupAry)) {

      for (int groupNo = 0; groupNo < groupAry.length; groupNo++) {
        if (Utility.isEmpty(groupAry[groupNo])) {
          continue;
        }
        try {
          TextUtility.stringValidation(groupAry[groupNo]);
        }
        catch (ApplicationException ex) {
          errorInfo.append("Group \"" + groupAry[groupNo] + "\"  is invaild; ");
        }
      }

    }

    // valitor role
    String[] roleAry = TextUtility.splitString(TextUtility.noNull(roles).trim(), ",");
    if (!Utility.isEmpty(roleAry)){
      for (int roleNo = 0; roleNo < roleAry.length; roleNo++) {
        if (Utility.isEmpty(roleAry[roleNo])) {
          continue;
        }
        try {
          TextUtility.stringValidation(roleAry[roleNo]);
        }
        catch (ApplicationException ex) {
          errorInfo.append("role \"" + roleAry[roleNo] + "\"  is invaild; ");
        }
      }
  }
    if (errorInfo.length() > 0) {
      data.setExceptionInfo(errorInfo.toString());
      throw new ApplicationException(new Exception(errorInfo.toString()));
    }
}
public  class ImportData {
    private String loginName;

    private String lastName;

    private String firstName;

    private String eMail;

    private String groups;

    private String roles;
    
    private String exceptionInfo;

    /**
     * 
     * @param loginName
     * @param lastName
     * @param firstName
     * @param email
     * @param group
     * @param role
     */
   public ImportData(String loginName,String lastName,String firstName,String email,String group,String role){
     this.loginName=loginName;
     this.lastName=lastName;
     this.firstName = firstName;
     this.eMail= email;
     this.groups=group;
     this.roles=role;
   }
    /**
     * @return the eMail
     */
    public String getEMail() {
      return eMail;
    }

    /**
     * @param mail the eMail to set
     */
    public void setEMail(String mail) {
      eMail = mail;
    }

    /**
     * @return the firstName
     */
    public String getFirstName() {
      return firstName;
    }

    /**
     * @param firstName the firstName to set
     */
    public void setFirstName(String firstName) {
      this.firstName = firstName;
    }

    /**
     * @return the groups
     */
    public String getGroups() {
      return groups;
    }

    /**
     * @param groups the groups to set
     */
    public void setGroups(String groups) {
      this.groups = groups;
    }

    /**
     * @return the lastName
     */
    public String getLastName() {
      return lastName;
    }

    /**
     * @param lastName the lastName to set
     */
    public void setLastName(String lastName) {
      this.lastName = lastName;
    }

    /**
     * @return the loginName
     */
    public String getLoginName() {
      return loginName;
    }

    /**
     * @param loginName the loginName to set
     */
    public void setLoginName(String loginName) {
      this.loginName = loginName;
    }

    /**
     * @return the roles
     */
    public String getRoles() {
      return roles;
    }

    /**
     * @param roles the roles to set
     */
    public void setRoles(String roles) {
      this.roles = roles;
    }
    /**
     * @return the exceptionInfo
     */
    public String getExceptionInfo() {
      return exceptionInfo;
    }
    /**
     * @param exceptionInfo the exceptionInfo to set
     */
    public void setExceptionInfo(String exceptionInfo) {
      this.exceptionInfo = exceptionInfo;
    }
  }

}

